/* global __DEVTOOLS__ */
import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';

// import * as reducers from '../reducers/index';
import rootReducer from '../reducers/index';

// const middleware = [thunkMiddleware]; // 允许我们 dispatch() 函数
const loggerMiddleware = createLogger({
  level: 'info',
  collapsed: true,
});

let createStoreWithMiddleware;
/* eslint-disable global-require,import/no-extraneous-dependencies */
if (typeof __DEVTOOLS__ !== 'undefined' && __DEVTOOLS__) {
  const { persistState } = require('redux-devtools');
  const DevTools = require('../containers/DevTools').default;
  createStoreWithMiddleware = compose(
    applyMiddleware(
      thunkMiddleware,
      loggerMiddleware,
    ),
    DevTools.instrument(),
    persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)),
  )(createStore);
} else {
  createStoreWithMiddleware = compose(
    applyMiddleware(
      thunkMiddleware,
      // promiseMiddleware
    ),
  )(createStore);
}

/**
 * Creates a preconfigured store.
 */
export default function configureStore(initialState) {
  const store = createStoreWithMiddleware(rootReducer, initialState);

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers/index');
      store.replaceReducer(nextRootReducer);
    });
  }

  return store;
}
